﻿
/*
 * 时间：2013年4月15日 23:54:28
 * 说明：打印借阅单
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using Microsoft.Practices.Unity;

using ePlanet.ArchiveBorrow.Models;
using ePlanet.ArchiveBorrow.Services;
using Web.SystemConfig.Services;
using ePlanet.ArchiveMange.DataAccess;
using ePlanet.ArchiveMange.Services;
using ePlanet.ArchiveMange.Enum;
using DreamBuilder.Core.Container;
using Web.SystemConfig.WorkFlow;

namespace Web.Views.ArchiveBorrow
{
    public partial class PrintArchiveBorrowList : PageBase
    {

        [Dependency]
        public IArchiveBorrowService m_IArchiveBorrowService
        {
            get;
            set;
        }

        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_User IUserService
        { get; set; }

        protected DataTable ArchiveDataTable
        {
            get;
            set;
        }

        protected DataTable LogDataTable
        {
            get;
            set;
        }

        protected string DataId
        {
            get
            {
                return Request.QueryString["DataID"];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ArchiveDataTable = new DataTable();
                ArchiveDataTable.Columns.Add("ARCHIVENUM", typeof(string));
                ArchiveDataTable.Columns.Add("TITLE", typeof(string));
                ArchiveDataTable.Columns.Add("ARCHIVESOURCE", typeof(string));
                ArchiveDataTable.Columns.Add("FILEORGID", typeof(string));

                LogDataTable = new DataTable();
                LogDataTable.Columns.Add("Department", typeof(string));
                LogDataTable.Columns.Add("SIGNUSERID", typeof(string));
                LogDataTable.Columns.Add("OPERATETIME", typeof(DateTime));
                LogDataTable.Columns.Add("COMMENTMESSAGE", typeof(string));

                if (string.IsNullOrEmpty(DataId))
                {
                    throw new ArgumentNullException("DataID");
                }

                try
                {
                    if (!m_IArchiveBorrowService.IsAllFinish(DataId))
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "noResult", "<script>alert('流程尚未结束，不能打印！');window.close();</script>");
                        return;
                    }

                    List<ArchiveBorrowModel> archiveBorrowModelList = m_IArchiveBorrowService.GetArchiveBorrowOrderData(DataId);

                    if (null == archiveBorrowModelList || 0 == archiveBorrowModelList.Count)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "noData", "<script>alert('没有借阅信息可以打印！');window.close();</script>");
                        return;
                    }

                    //利用信息
                    ArchiveBorrowModel.ARCHIVEBORROWRow archiveBorrowModel = archiveBorrowModelList[0].ARCHIVEBORROW[0];
                    lblUserName.Text = archiveBorrowModel.BORROWUSERNAME ?? string.Empty;
                    lblDepartment.Text = archiveBorrowModel.USERORGNAME ?? string.Empty;
                    lblPhoneNumber.Text = archiveBorrowModel.TELNUM ?? string.Empty;
                    lblIDCard.Text = archiveBorrowModel.IDCARD ?? string.Empty;
                    lblBorrowDate.Text = archiveBorrowModel.CREATETIME.Date.ToString("yyyy-MM-dd");
                    lblBorrowReason.Text = archiveBorrowModel.BORROWREASON ?? string.Empty;

                    foreach (ListItem item in cblARCHIVETYPE.Items)
                    {
                        if (archiveBorrowModel.ARCHIVETYPE.Contains(item.Value))
                        {
                            item.Selected = true;
                        }
                    }

                    foreach (ListItem item in cblUSERTYPE.Items)
                    {
                        if (archiveBorrowModel.USERTYPE.Contains(item.Value))
                        {
                            item.Selected = true;
                            if (item.Value.Equals("3"))
                            {
                                item.Text = string.Format("复制_{0}_页", archiveBorrowModel.COPYPAGE);
                            }
                        }
                    }

                    //绑定档案条目
                    int baseTypeId = ArchiveMenuService.GetArchiveBaseIDById((int)archiveBorrowModel.ARCHIVETYPEID);

                    List<string> myIdList = new List<string>();
                    foreach (ArchiveBorrowModel model in archiveBorrowModelList)
                    {
                        myIdList.Add(model.ARCHIVEBORROW[0].ARCHIVEDATAID);
                    }

                    switch (baseTypeId)
                    {
                        //文书类
                        case ((int)ArchiveBaseType.Document):
                            IDocumentArchiveService documentArchiveService = UContainer.Resolve<IDocumentArchiveService>();
                            ArchiveDataTable = documentArchiveService.GetDocumentArchiveDataByIds(myIdList);
                            break;
                        //会计类
                        case ((int)ArchiveBaseType.Account):
                            IAccountArchiveService accountArchiveService = UContainer.Resolve<IAccountArchiveService>();
                            ArchiveDataTable = accountArchiveService.GetAccountArchiveDataByIds(myIdList);
                            break;
                        //基建类
                        case ((int)ArchiveBaseType.BulidProject):
                            IBuildProjectArchiveService buildProjectService = UContainer.Resolve<IBuildProjectArchiveService>();
                            ArchiveDataTable = buildProjectService.GetBuildProjectArchiveDataByIds(myIdList);
                            break;
                        //设备类
                        case ((int)ArchiveBaseType.Equipment):
                            IEquipmentService equipService = UContainer.Resolve<IEquipmentService>();
                            ArchiveDataTable = equipService.GetEquipmentArchiveDataByIds(myIdList);
                            break;
                        //油气勘探类
                        case ((int)ArchiveBaseType.OliSearch):
                            IOilSearchArchiveService oliSearchService = UContainer.Resolve<IOilSearchArchiveService>();
                            ArchiveDataTable = oliSearchService.GetOilSearchArchiveDataByIds(myIdList);
                            break;
                        //音像类
                        case ((int)ArchiveBaseType.AudioVedio):
                            IAudioArchiveService audioService = UContainer.Resolve<IAudioArchiveService>();
                            ArchiveDataTable = audioService.GetAudioArchiveDataByIds(myIdList);
                            break;
                        //实物类
                        case ((int)ArchiveBaseType.RealKind):
                            IRealKindArchiveService realService = UContainer.Resolve<IRealKindArchiveService>();
                            ArchiveDataTable = realService.GetRealKindArchiveDataByIds(myIdList);
                            break;
                        //科研类
                        case ((int)ArchiveBaseType.Technology):
                            ITechArchiveService techService = UContainer.Resolve<ITechArchiveService>();
                            ArchiveDataTable = techService.GetTechArchiveDataByIds(myIdList);
                            break;
                        //光盘类
                        case ((int)ArchiveBaseType.CDKind):
                            ICDArchiveService cdService = UContainer.Resolve<ICDArchiveService>();
                            ArchiveDataTable = cdService.GetCDArchiveDataByIds(myIdList);
                            break;
                        case 101:
                            IDocumentArchiveVolService documentVolService = UContainer.Resolve<IDocumentArchiveVolService>();
                            ArchiveDataTable = documentVolService.GetDocumentArchiveDataByIds(myIdList);
                            break;
                        case 102:
                            IDocumentArchiveVolFileService documentVolFileService = UContainer.Resolve<IDocumentArchiveVolFileService>();
                            ArchiveDataTable = documentVolFileService.GetDocumentArchiveDataByIds(myIdList);
                            break;
                        case 7101:
                            IZongheVolService zongheVolService = UContainer.Resolve<IZongheVolService>();
                            ArchiveDataTable = zongheVolService.GetZongheVolDataByIds(myIdList);
                            break;
                        case 7102:
                            IZongheVolFileService zongheVolFileService = UContainer.Resolve<IZongheVolFileService>();
                            ArchiveDataTable = zongheVolFileService.GetZongheVolFileDataByIds(myIdList);
                            break;
                    }

                    while (ArchiveDataTable.Rows.Count < 10)
                    {
                        ArchiveDataTable.Rows.Add(ArchiveDataTable.NewRow());
                    }

                    //绑定审核流程
                    DataTable logDt = this.GetWorkFlowLog(DataId);
                    if (logDt == null) return;
                    DataRow[] BBSLDCommentRows = logDt.Select("OperateID in (1001,1002) and FromStatusID=501 and islast=0");//本部室领导意见
                    //DataRow[] XXZXDAYCommentRows = logDt.Select("OperateID in (1003,1004,1005) and FromStatusID=502 and islast=0");//档案员审批意见
                    DataRow[] DAXCBMLDComnentRows = logDt.Select("OperateID in (1006,1007) and FromStatusID=503 and islast=0");//档案形成部门审批意见
                    DataRow[] XXZXLDYJCommentRows = logDt.Select("OperateID in (1008,1009) and FromStatusID=504 and islast=0");//信息中心领导审批意见
                    //DataRow[] XXZXDAYCommentRowsWC = logDt.Select("OperateID =1011 and FromStatusID=506  and islast=0");//档案员发起借阅，档案员审批意见
                    DataRow[] DAXCBMLDComnentRowsWC = logDt.Select("OperateID in (1012,1013) and FromStatusID=507");//档案员发起借阅，档案形成部门审批意见

                    //绑定日志
                    DataTable newLogTable = LogDataTable.Clone();
                    AddRow(ref newLogTable, "档案利用者单位", BBSLDCommentRows);
                    if (DAXCBMLDComnentRows.Length > 0)
                    {
                        AddRow(ref newLogTable, "档案形成单位", DAXCBMLDComnentRows);
                    }
                    else
                    {
                        AddRow(ref newLogTable, "档案形成单位", DAXCBMLDComnentRowsWC);
                    }

                    AddRow(ref newLogTable, "档案管理部门", XXZXLDYJCommentRows);

                    foreach (DataRow row in newLogTable.Rows)
                    {
                        if (row["SIGNUSERID"] != null && row["SIGNUSERID"] != DBNull.Value)
                        {
                            row["SIGNUSERID"] = IUserService.GetUserNameById(row["SIGNUSERID"].ToString());
                        }
                    }

                    DataView dv = newLogTable.DefaultView;

                    LogDataTable = dv.ToTable();
                }
                catch (System.Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "exceptionResult", "<script>alert('生成借阅单发生异常！');</script>");
                }


            }
        }

        private int CompareDateDesc(DataRow a, DataRow b)
        {
            DateTime da = DateTime.Parse(a["operatetime"].ToString());
            DateTime db = DateTime.Parse(b["operatetime"].ToString());
            int cmpResult = da.CompareTo(db);
            if (cmpResult > 0)
            {
                return -1;
            }
            else if (cmpResult < 0)
                return 1;
            else return 0;
        }

        private void AddRow(ref DataTable table, string department, DataRow[] rows)
        {
            if (rows != null)
            {
                DataRow r = null;
                if (rows.Length > 1)
                {
                    r = rows.First(row => row["signuserid"] != DBNull.Value);
                }
                else if (rows.Length == 1)
                {
                    //table.Rows.Add(rows[0].ItemArray);
                    r = rows[0];
                }

                var newRow = table.NewRow();
                newRow["Department"] = department;

                if (string.Equals("档案管理部门", department))
                {
                    newRow["SIGNUSERID"] = r != null ? r["FromUserID"] : DBNull.Value;
                }
                else
                {
                    newRow["SIGNUSERID"] = r != null ? r["FromUserID"] : DBNull.Value;
                }
                newRow["OPERATETIME"] = r != null ? r["OPERATETIME"] : DBNull.Value;
                newRow["COMMENTMESSAGE"] = r != null ? r["COMMENTMESSAGE"] : DBNull.Value;

                if (table.Select(string.Format("Department='{0}'", department)).Length == 0)
                    table.Rows.Add(newRow);
            }
        }

        private void AddRowToList(ref List<DataRow> rowList, DataRow[] rows)
        {
            if (rows != null && rows.Length > 0)
            {
                if (rows.Length > 1)
                {
                    DataRow r = rows.First(row => row["signuserid"] != DBNull.Value);
                    rowList.Add(r);
                }
                else
                {
                    rowList.Add(rows[0]);
                }
            }
        }

        /// <summary>
        /// 获取操作日志
        /// </summary>
        /// <param name="dataID"></param>
        /// <returns></returns>
        private DataTable GetWorkFlowLog(string dataID)
        {
            WorkFlow oWorkFlow = new WorkFlow();
            return oWorkFlow.GetOperateLogList(ArchiveTableEnum.ArchiveBorrow, dataID);
        }

        /// <summary>
        /// 审核日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvExamFlowList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                e.Row.Cells[0].Text = IUserService.GetUserNameById(row["SIGNUSERID"].ToString());
            }
        }
    }
}